package com.demo.netty.service;

import com.demo.netty.model.ChatMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class ReconnectService {
    private static final Logger logger = LoggerFactory.getLogger(ReconnectService.class);
    
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    
    private static final String RECONNECT_KEY_PREFIX = "reconnect_token:";
    private static final long TOKEN_EXPIRE_TIME = 30; // 30分钟
    
    /**
     * 生成重连令牌
     */
    public String generateReconnectToken(String userId) {
        String token = java.util.UUID.randomUUID().toString();
        String key = RECONNECT_KEY_PREFIX + userId;
        
        try {
            redisTemplate.opsForValue().set(key, token, TOKEN_EXPIRE_TIME, TimeUnit.MINUTES);
            logger.info("为用户 {} 生成重连令牌: {}", userId, token);
            return token;
        } catch (Exception e) {
            logger.error("生成重连令牌失败", e);
            return null;
        }
    }
    
    /**
     * 验证重连令牌
     */
    public boolean validateReconnectToken(String userId, String token) {
        String key = RECONNECT_KEY_PREFIX + userId;
        
        try {
            String storedToken = (String) redisTemplate.opsForValue().get(key);
            if (storedToken != null && storedToken.equals(token)) {
                // 验证成功后删除令牌
                redisTemplate.delete(key);
                logger.info("用户 {} 重连令牌验证成功", userId);
                return true;
            }
        } catch (Exception e) {
            logger.error("验证重连令牌失败", e);
        }
        
        logger.warn("用户 {} 重连令牌验证失败", userId);
        return false;
    }
    
    /**
     * 保存用户会话状态
     */
    public void saveUserSession(String userId, ChatMessage lastMessage) {
        String key = "user_session:" + userId;
        
        try {
            redisTemplate.opsForValue().set(key, lastMessage, TOKEN_EXPIRE_TIME, TimeUnit.MINUTES);
            logger.info("保存用户 {} 会话状态", userId);
        } catch (Exception e) {
            logger.error("保存用户会话状态失败", e);
        }
    }
    
    /**
     * 恢复用户会话状态
     */
    public ChatMessage restoreUserSession(String userId) {
        String key = "user_session:" + userId;
        
        try {
            ChatMessage lastMessage = (ChatMessage) redisTemplate.opsForValue().get(key);
            if (lastMessage != null) {
                logger.info("恢复用户 {} 会话状态", userId);
                return lastMessage;
            }
        } catch (Exception e) {
            logger.error("恢复用户会话状态失败", e);
        }
        
        return null;
    }
}